<template>
  <div>
    <div class="ksd-search-container">
      <el-button type="danger" @click="handleBatchDel"><el-icon :size="20"> <Edit /></el-icon>批量删除</el-button>
      <el-select v-model="pageInfo.categoryId" style="margin-left: 10px;" clearable class="m-2" placeholder="请选择分类" size="large" @change="handleSearch" @clear="pageInfo.categoryId=null">
        <el-option
          v-for="item in categoryList"
          :key="item.ID"
          :label="item.title"
          :value="item.ID"
        />
      </el-select>
      <el-input
        v-model="pageInfo.keyword"
        clearable
        class="w-50"
        size="small"
        :input-style="{ 'width': '240px', 'margin': '0 10px' }"
        placeholder="请输入分类名称"
        :suffix-icon="Search"
      />
      <el-button type="success" style="margin-left: 40px;" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
    </div>
    <el-table v-loading="loading" :data="pageInfo.resultList" max-height="calc(100vh -300px)" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed label="ID" prop="ID" align="center" width="80" />
      <el-table-column label="标题" prop="title" width="240" />
      <el-table-column label="描述" prop="description" width="240" align="center" />
      <el-table-column label="分类" prop="categoryName" width="100" align="center" />
      <el-table-column label="浏览数" prop="viewCount" width="80" align="center" />
      <el-table-column label="评论数" prop="comments" width="80" align="center" />
      <el-table-column label="是否允许评论" width="150" align="center">
        <template #default="scope">
          <span v-if="scope.row.commentsOpen === 1" style="color:green">允许</span>
          <span v-if="scope.row.commentsOpen === 0" style="color:red">不允许</span>
        </template>
      </el-table-column>
      <el-table-column label="发帖人" prop="username" width="100" />
      <el-table-column label="发帖时间" prop="createdAt" width="220" />
      <el-table-column label="更新时间" prop="updatedAt" width="220" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <span v-if="scope.row.status === 1" style="color:green">已发布</span>
          <span v-if="scope.row.status === 0" style="color:red">未发布</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="160">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)"><el-icon><Edit /></el-icon>编辑</el-button>
          <el-button size="small" type="danger" icon="Delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" style="display:flex;justify-content: center;">
      <el-pagination
        :current-page="pageInfo.page"
        :page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 30, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!--分类添加和编辑 :close-on-press-escape="false" :close-on-click-modal="false"-->
    <el-dialog
      v-model="dialogVisible"
      title="添加分类"
      width="600px"
      :before-close="handleClose"
    >
      <!--      {{ bbsInfo }}-->
      <el-form
        ref="bbsFormRef"
        :model="bbsInfo"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="bbsInfo.title" placeholder="请输入标题" maxlength="50" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="bbsInfo.description" type="textarea" placeholder="请输入描述" maxlength="50" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="bbsInfo.categoryId" clearable class="m-2" placeholder="Select" size="large" @change="handleChangeCategoty" @clear="bbsInfo.categoryId=null">
            <el-option
              v-for="item in categoryList"
              :key="item.ID"
              :label="item.title"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否允许评价" prop="status">
          <el-radio-group v-model="bbsInfo.commentsOpen" class="ml-4">
            <el-radio :label="1">允许</el-radio>
            <el-radio :label="0">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="bbsInfo.status" class="ml-4">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除状态" prop="isDelete">
          <el-radio-group v-model="bbsInfo.isDelete" class="ml-4">
            <el-radio :label="1">已删除</el-radio>
            <el-radio :label="0">未删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit"><el-icon><Check /></el-icon>保存</el-button>
          <el-button @click="handleCloseDialog"><el-icon><Close /></el-icon>关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { loadBbsData, delBbses, delBbs, updateBbs } from '@/api/bbslist.js'
import { findBbsCategory } from '@/api/bbscategory.js'

import { onMounted, reactive, ref } from 'vue'
// import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import Ksd from '@/utils/index.js'
// 这里是添加和编辑-------------------------------------------
const dialogVisible = ref(false)
const formSize = ref('default')
const bbsFormRef = ref(null)
const bbsInfo = reactive({
  title: '',
  description: '',
  categoryId: null,
  categoryName: 0,
  commentsOpen: 1,
  status: 1,
  isDelete: 0
})
const rules = reactive({
  title: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
})

// 打开编辑
const handleEdit = (index, row) => {
  bbsInfo.ID = row.ID
  bbsInfo.title = row.title
  bbsInfo.description = row.description
  bbsInfo.categoryId = row.categoryId
  bbsInfo.categoryName = row.categoryName
  bbsInfo.commentsOpen = row.commentsOpen
  bbsInfo.status = row.status
  bbsInfo.isDelete = row.isDelete
  // 数据回填form
  dialogVisible.value = true
}

// 关闭添加和编辑
const handleCloseDialog = () => {
  dialogVisible.value = false
}

// 弹窗关闭
const handleClose = () => {
  handleCloseDialog()
}

const handleChangeCategoty = (e) => {
  console.log(e)
}

// 保存和编辑
const handleSubmit = async() => {
  await bbsFormRef.value.validate(async(valid, fields) => {
    if (valid) {
      let res
      let message = '添加成功'
      const param = bbsInfo
      if (param.categoryId) {
        categoryList.value.forEach(item => {
          if (item.ID === param.categoryId) {
            param.categoryName = item.title
          }
        })
      } else {
        param.categoryId = -1
      }
      if (param.ID) {
        message = '编辑成功'
        res = await updateBbs(param)
      } else {
        console.log('保存逻辑')
      }

      if (res.code === 0) {
        // 关闭当前添加窗口
        handleCloseDialog()
        // 重置model对象
        bbsFormRef.value.resetFields()
        bbsFormRef.value.clearValidate()
        // 添加刷新当前页
        handleLoadData()
        ElMessage({
          message,
          type: 'success',
        })
      }
    }
  })
}

// 这里是查询-------------------------------------------------

// 1: 设置请求分页的参数
const pageInfo = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  status: -1,
  resultList: [],
  keyword: '',
  categoryId: null,
})

// 2: 数据加载
const handleLoadData = async() => {
  loading.value = true
  const param = {...pageInfo}
  if (!param.categoryId) {
    param.categoryId = -1
  }
  const res = await loadBbsData(param)
  loading.value = false
  pageInfo.total = res.data.total
  pageInfo.resultList = res.data.list
}

// 搜索
const handleSearch = async() => {
  pageInfo.page = 1
  pageInfo.resultList = []
  await handleLoadData()
}

// 点击分页改变
const handleCurrentChange = (pageNum) => {
  pageInfo.page = pageNum
  handleLoadData()
}

// 批量状态的事件
const handleSelectionChange = (rows) => {
  ids.value = rows.map(row => row.ID)
}

// 点击每页显示多少条改变
const handleSizeChange = (pageSize) => {
  pageInfo.pageSize = pageSize
  handleLoadData()
}

// 接收分类列表
const categoryList = ref([])

// 加载帖子分类
const handleLoadCategoryData = async() => {
  const res = await findBbsCategory()
  categoryList.value = res.data
  // categoryList.value.unshift({ ID: -1, title: '请选择分类' })
}

// 根据id删除
const handleDelete = async(index, row) => {
  const result = await Ksd.confirm('提示', '你确定要抛弃我吗？', { cbtn: '容我想想', sbtn: '直接删了', type: 'error' })
  if (result === 'confirm') {
    const res = await delBbs(row.ID)
    if (res.data === 'ok') {
      Ksd.success('删除成功!!!')
      await handleLoadData()
    }
  }
}

// 获取删除的ids
const ids = ref([])
const loading = ref(false)

// 批量删除
const handleBatchDel = async() => {
  if (ids.value.length === 0) {
    Ksd.warn('请选择一项进行操作!!!')
    return
  }
  const result = await Ksd.confirm('提示', '你确定执行【批量删除】吗?')
  if (result === 'confirm') {
    const idstrings = ids.value.join(',')
    const res = await delBbses(idstrings)
    if (res.data === 'ok') {
      Ksd.success('删除成功!!!')
      await handleLoadData()
    }
  }
}

// 3: 生命周期初始化数据加载
onMounted(() => {
  // 加载帖子列表
  handleLoadData()
  // 加载数据分类
  handleLoadCategoryData()
})
</script>

<style scoped lang="scss">
.ksd-search-container{
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding:6px;
  background: #f7fbff;
}
</style>
